package framework.rpc.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import framework.rpc.protocol.register.RegisterUrl;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

public class IoUtil {
    public static void main(String[] args) {
        try {
            InputStream inputStream = new FileInputStream("D:\\Workspace\\java-design-mode\\framework-rpc\\test.txt");
             System.out.println("开始读取内容");
            System.out.println("读取内容为："+ read(inputStream));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void write(String content,OutputStream outputStream){
        try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
            writer.write(content);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String read(InputStream inputStream) {
        try {
            InputStreamReader bis = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(bis);
            StringBuilder buffer = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                 System.out.println(line);
                buffer.append(line);
            }
            inputStream.close();
            bis.close();
            return buffer.toString();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    public static void save(Map<String, List<RegisterUrl>> map){
        try{
            FileOutputStream fos = new FileOutputStream("D:\\Workspace\\java-design-mode\\framework-rpc\\registry_center.properties");
            OutputStreamWriter writer =new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            writer.write(JSONObject.toJSONString(map));
            writer.flush();
            writer.close();
        }catch (Exception e){
             System.out.println(e.getMessage());
        }
    }
}
